package com.feiyutech.camera2demo

import android.app.AlertDialog
import android.hardware.camera2.CameraMetadata
import android.hardware.camera2.CaptureRequest
import android.os.Bundle
import cn.zfs.common.utils.ImageUtils
import kotlinx.android.synthetic.main.activity_flash.*
import java.io.File

/**
 * 描述:
 * 时间: 2018/8/4 22:10
 * 作者: zengfansheng
 */
class FlashActivity : BaseCameraActivity() {
    private var checkItem = 0
    
    override fun updateCaptrueRequestBuilder(builder: CaptureRequest.Builder) {
        builder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE)
        setFlashMode(builder, checkItem)
    }

    override fun getTextureView() = textureView!!

    override fun getPictureSaveResultListener() = saveResultListener
    
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_flash)
        title = "闪光灯设置"
        btnCapture.setOnClickListener { takeCapture() }
        ivFlash.setColorFilter(0xFFFFE049.toInt())
        ivFlash.setOnClickListener {
            AlertDialog.Builder(this).setSingleChoiceItems(arrayOf("关闭", "自动", "打开", "常亮"), checkItem) { dialog, which ->  
                setFlashMode(previewRequestBuilder, which)
                updatePreview()
                ivFlash.setImageLevel(which)
                checkItem = which
                dialog.dismiss()
            }.show()
        }
    }
    
    private fun setFlashMode(builder: CaptureRequest.Builder?, mode: Int) {
        when (mode) {
            0 -> {
                builder?.set(CaptureRequest.CONTROL_AE_MODE, CameraMetadata.CONTROL_AE_MODE_ON)
                builder?.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_OFF)
            }
            1 -> builder?.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH)
            2 -> builder?.set(CaptureRequest.CONTROL_AE_MODE, CameraMetadata.CONTROL_AE_MODE_ON_ALWAYS_FLASH)
            3 -> {
                builder?.set(CaptureRequest.CONTROL_AE_MODE, CameraMetadata.CONTROL_AE_MODE_ON)
                builder?.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_TORCH)
            }
        }
    }
    
    private val saveResultListener = object : JpegReaderListener.OnSaveResultListener {
        override fun onSaveResult(file: File?) {
            if (file != null) {
                val bitmap = ImageUtils.getBitmap(file.absolutePath, ivResult.width, ivResult.height)
                if (bitmap != null) {
                    runOnUiThread { ivResult.setImageBitmap(bitmap) }
                }
            }
        }
    }
}